from flask import Blueprint,request,make_response,jsonify,redirect
from utils.sendmobile import send_message
from utils.captcha.captcha import captcha
from utils.myjwt import myjwt
import json, random, time, requests
from utils.myredis import r
from models.models import *
from utils.md5 import md5

user_blue = Blueprint("userblue",__name__)


@user_blue.route("/getImageCode")
# 图片验证码
def getImageCode():
    # 生成图片验证码 text文字   image图片流
    name, text, image = captcha.generate_captcha()
    print("图片验证码>>>", text)
    # 从页面获取uuid做为redis key
    uuid = request.args.get("uuid")
    # 存入redis
    r.str_setex(uuid, text, 300)
    # 以流的方式生成图片验证码
    res = make_response(image)
    res.headers["Content-Type"] = 'image/jpg'
    return res

@user_blue.route("/sms_code",methods=["POST"])
# 获取手机验证码按钮校验
def sms_code():
    data = json.loads(request.data)
    mobile = data["mobile"]
    # 图片验证码
    image = data["image"]
    uuid = data["uuid"]
    if not all([mobile,image]):
        return jsonify({"code": 400, "msg":"字段不完整,请先输入图片验证码"})
    # 从redis中取出uuid
    res = r.str_get(uuid)
    if res:
        # 判断图片验证码是否正确
        if res.decode().lower() != image.lower():
            return jsonify({"code": 400, "msg": "图片验证码错误"})
        # 删除存在redis中的uuid
        r.del_key(uuid)
    else:
        return jsonify({"code": 400, "msg": "图片验证码已过期"})
    # 一分钟只能发送一次验证码，先判断队列里是否有
    j = r.str_get(mobile)
    if j:
        return jsonify({"code": 400, "msg": "一分钟只能发送一次"})
    # 如果没有，就将当前手机号加入redis
    r.list_push("sendmobile",mobile)
    return jsonify({"code": 200, "msg": "发送成功"})

@user_blue.route("/send")
# 获取验证码
def send():
    while True:
        for i in range(2):
            # 查看队列长度
            len = r.list_len("sendmobile")
            if len > 0:
                # 获取队列中的手机号
                data = r.list_pop("sendmobile")
                # 解码
                mobile = data.decode()
                # 获取四位随机数
                code = random.randint(10000,99999)
                print("手机验证码>>>",code)
                # 获取手机验证码
                res = send_message(mobile,code)
                print(res)
                # 将手机号和验证码加入redis
                r.str_setex(mobile, code, 60)
        time.sleep(1)
        return jsonify({"code": 200, "msg": "获取验证码成功"})

@user_blue.route("/login",methods=["POST"])
# 登录/注册
def login():
    data = json.loads(request.data)
    mobile = data["mobile"]
    roleid = data["roleid"]
    password = data["password"]
    # 密码加密
    password = md5(password)
    sms_mobile = data["sms_mobile"]
    if not all([mobile,roleid,sms_mobile,password]):
        return jsonify({"code":400,"msg":"字段不完整"})
    s = r.str_get(mobile)
    if s:
        if json.dumps(s.decode()) != json.dumps(sms_mobile):
            return jsonify({"code": 400, "msg": "手机验证码错误"})
        r.del_key(mobile)
        user = User.query.filter_by(mobile=mobile).first()
        if user:
            if password != user.password:
                return jsonify({"code": 400, "msg": "密码错误"})
            data = {"data":{"userid": user.id, "mobile": user.mobile, "exptime": int(time.time())}}
            token = myjwt.jwt_encode(data)
            return jsonify({"code": 200, "msg": "登录成功", "token": token, "userid": user.id, "mobile": user.mobile})
        else:
            ad = User(mobile=mobile,password=password,roleid=roleid)
            db.session.add(ad)
            db.session.commit()
            data = {"data": {"userid": ad.id, "mobile": ad.mobile, "exptime": int(time.time())}}
            token = myjwt.jwt_encode(data)
            return jsonify({"code": 200, "msg": "注册并登录成功", "token": token, "userid": ad.id, "mobile": ad.mobile})
    else:
        return jsonify({"code": 400, "msg": "手机验证码过期"})

@user_blue.route("/getroles")
# 获取全部角色
def getroles():
    data = Roles.query.all()
    lst = []
    for i in data:
        lst.append({
            "id":i.id,
            "name":i.name
        })
    return jsonify({"code": 200, "msg": "获取成功","data":lst})

@user_blue.route("/wburl")
# 三方登录,获取url
def wburl():
    client_id = "3674019597"
    redirect_uri = "http://127.0.0.1:8000/user/weiboCallback/"
    # 微博平台地址
    url = "https://api.weibo.com/oauth2/authorize?client_id=%s&redirect_uri=%s&response_type=code" % (
        client_id, redirect_uri)
    return jsonify({"code": 200, 'url': url})

@user_blue.route("/user/weiboCallback/")
# 微博回调
def weiboCallback():
    # 获取code
    code = request.args.get("code")
    # print("code",code)
    # 向access_token接口发送post请求
    data = {"client_id": '3674019597', "client_secret": "7ae99bc0d54ead29fc8d1b9fabd78587",
            "grant_type": "authorization_code",
            'redirect_uri': 'http://127.0.0.1:8000/user/weiboCallback/', 'code': code}
    # 获取https://api.weibo.com/oauth2/access_token信息  token   uid
    res = requests.post('https://api.weibo.com/oauth2/access_token', data=data)
    # 根据返回结果操作
    # 先json转为字点获取token和uid
    message = json.loads(res.text)
    token = message['access_token']
    uid = message['uid']
    # 查询uid在数据库中是否存在，如果存在用用户信息生成jwt token返回
    wb = db.session.execute("select user.id,user.mobile from sf_login inner join user on sf_login.userid=user.id where sf_login.uid='%s'"%(str(uid)))
    wb1 = list(wb)
    # 如果存在
    if wb1:
        # 生成返回token
        for i in wb1:
            # print("i",i)
            token = myjwt.jwt_encode(
                data={"data": {"uid": i[0], "mobile": i[1], 'exp': int(time.time())}})
            # 生成token，跳转到vue中转页，保存token到
            return redirect("http://localhost:8080/about?token=" + token + "&userid=" + str(i[0]))
    else:
        # 不存在，就跳转到绑定手机号页面
        return redirect("http://localhost:8080/wblogin?token=" + str(token) + "&uid=" + str(uid))

@user_blue.route("/sflogin",methods=["POST"])
# 三方登录绑定手机号页面
def sflogin():
    data = json.loads(request.data)
    # 判断手机号是否在用户表中存在
    user = User.query.filter_by(mobile=data["mobile"]).first()
    if user:
        # 加入三方登录表
        sf = Sf_login(userid=user.id,webfrom="weibo",uid=data["uid"],token=data["token"])
        db.session.add(sf)
        db.session.commit()
        # 生成token
        data = {"data":{"userid":user.id,"mobile":user.mobile,"exptime":int(time.time())}}
        token = myjwt.jwt_encode(data)
        return jsonify({"code": 200, "msg": "登录成功", "token": token, "userid": user.id, "mobile": user.mobile})
    else:
        try:
            password = md5(data["password"])
            # 加入用户表
            admin = User(mobile=data["mobile"],roleid=1,password=password)
            db.session.add(admin)
            db.session.commit()
            # 加入三方登录表
            sf = Sf_login(userid=admin.id,webfrom="weibo",uid=data["uid"],token=data["token"])
            db.session.add(sf)
            db.session.commit()
            # 生成token
            data = {"data": {"userid": admin.id, "mobile": admin.mobile, "exptime": int(time.time())}}
            token = myjwt.jwt_encode(data)
            return jsonify({"code": 200, "msg": "登录成功", "token": token, "userid": admin.id, "mobile": admin.mobile})
        except Exception as a:
            print(a)
            return jsonify({"code":400,"msg":"错误"})


































